
var clientPC = navigator.userAgent.toLowerCase();
var clientVer = parseInt(navigator.appVersion);
var is_ie = ((clientPC.indexOf("msie") != -1) && (clientPC.indexOf("opera") == -1));
var is_win = ((clientPC.indexOf("win")!=-1) || (clientPC.indexOf("16bit") != -1));
var set_on = false;

	//alert(document.domain);
try{
	//document.domain = 'www.townwars.ru';
}catch(e){
	//document.domain = 'gopota.loc';
}

var _doc = function() {
	return parent;
}
function getparent(){
	if(globalPernt){
		return true;
	}
	return false;
}

function countHash(hash){
	var counter = 0;
    for( var k in hash )
        counter++
    return counter

}

function message(mes)
{
	alert(mes);
}



function setCookie (name, value, expires, path, domain, secure) {
      document.cookie = name + "=" + escape(value) +
        ((expires) ? "; expires=" + expires : "") +
        ((path) ? "; path=" + path : "") +
        ((domain) ? "; domain=" + domain : "") +
        ((secure) ? "; secure" : "");
}

function getCookie(name) {
	var cookie = " " + document.cookie;
	var search = " " + name + "=";
	var setStr = null;
	var offset = 0;
	var end = 0;
	if (cookie.length > 0) {
		offset = cookie.indexOf(search);
		if (offset != -1) {
			offset += search.length;
			end = cookie.indexOf(";", offset)
			if (end == -1) {
				end = cookie.length;
			}
			setStr = unescape(cookie.substring(offset, end));
		}
	}
	return(setStr);
}


function FindByNick()
{
	var nick = $("#searchByName").val(); 
	windowManfredi.getObject('ajax')._close(); 
	getAjax({c: 'Info', m: 'Index', div:'dialog', name:nick});
}

function openDialog(param){
	if(!param){
		var param = {};
		param.title = $("#title_dialog", document.parent).html();		
		$("#title_dialog", document.parent).html("");		
		param.cont = $("#content_dialog", document.parent).html();		
		$("#content_dialog", document.parent).html("");		
	}
		
	
	var win_id = (param.win_id) ? param.win_id : "ajax" ; 
	windowManfredi.getObject(win_id,param['title'],param['cont'])._init();
	
	//$("#dialog").show();
	//$("#blockFrame").show();
}
/*function closeDialog(){	
	$("#dialog").hide();
	//$("#blockFrame").hide();
	$("#title_dialog").html();
	$("#content_dialog").html();
}*/

function ajaxRequest(backend,hash,onRredyFunction){
	var req = new JsHttpRequest();
	    req.onreadystatechange = function() {
	        if (req.readyState == 4) {
	        	ajaxBackend(req.responseJS,req.responseText);
	        	if(onRredyFunction!=undefined){
	        		eval(onRredyFunction);
	        	}
	        }
	    }
	    req.open(null, '/'+backend, false);
	    req.send(hash);
}

function print_r( array, return_val ) {    // Prints human-readable information about a variable

    var output = "", pad_char = " ", pad_val = 4;
 
    var formatArray = function (obj, cur_depth, pad_val, pad_char) {
        if(cur_depth > 0)
            cur_depth++;
 
        var base_pad = repeat_char(pad_val*cur_depth, pad_char);
        var thick_pad = repeat_char(pad_val*(cur_depth+1), pad_char);
        var str = "";
 
        if(obj instanceof Array || obj instanceof Object) {
            str += "Array\n" + base_pad + "(\n";
            for(var key in obj) {
                if(obj[key] instanceof Array || obj[key] instanceof Object) {
                    str += thick_pad + "["+key+"] => "+formatArray(obj[key], cur_depth+1, pad_val, pad_char);
                } else {
                    str += thick_pad + "["+key+"] => " + obj[key] + "\n";
                }
            }
            str += base_pad + ")\n";
        } else {
            str = obj.toString();
        };
 
        return str;
    };
 
    var repeat_char = function (len, chr) {
        var str = "";
        for(var i=0; i < len; i++) { str += chr; };
        return str;
    };
 
    output = formatArray(array, 0, pad_val, pad_char);
 
    if(return_val !== true) {
        return output;
        //document.write("<pre>" + output + "</pre>");
        //return true;
    } else {
        return output;
    }
}

function loadAjax(hash, callBack){
	if(!hash){
		var hash = {};
	}
	if(!hash.ajax)
	{
		hash.ajax = 1;
	}
	params = $.param(hash);
	$.post('/', hash, function(json){
		if(json.error!="") $("#debug").html((json.error));
		/*$("#content_dialog").html(json.error);
		openDialog();*/
		$("#debug").css('padding', '5px');
		$("#debug").append((json));
		if(json.result && callBack == null){
			for(key in json.result){
				var tmp = json.result[key];			
				if(tmp["redirect"]){
					top.location=tmp["redirect"];
				}		
				if(tmp["act"]==0){
					$("#"+tmp["div"]).html(tmp["cont"]);
				}else if(tmp["act"]==1){
					$("#"+tmp["div"]).append(tmp["cont"]);
				}else if(tmp["act"]==2){
					$("#"+tmp["div"]).prepend(tmp["cont"]);
				}else if(tmp["act"]==3){
					$("#"+tmp["div"]).html("");
				}			
				if(tmp["style"]){
					for(var k in tmp["style"]){
						$("#"+tmp["div"]).css([k],tmp["style"][k]);
					}
				}
				if(tmp["js"]){
					eval(tmp["js"]);
				}
						
			}
		}else if(json.result && callBack){
			callBack(json.result);
		
		}
		
		if(json.debug)
		{
			var html = '<br><br>';
			var sql = [];
			var param = [];
			html = print_r(json.debug, false);
		}
	}, "json");	
}

function getAjax(hash, callBack){
	if(callBack){
		callBack = null;
	}
	if(window.frames['gameFrame']){
		window.frames['gameFrame'].loadAjax(hash);
	}else{
		loadAjax(hash, callBack);
	}
}

function var_dump(obj) {
   if(typeof obj == "object") {
      return "Type: "+typeof(obj)+((obj.constructor) ? "\nConstructor: "+obj.constructor : "")+"\nValue: " + obj;
   } else {
      return "Type: "+typeof(obj)+"\nValue: "+obj;
   }
}

function ajaxBackend(result,error){	
	//alert(var_dump(result));



	if(error){
		if($('#dialog')){
			$("#content_dialog").html(error);
			openDialog();
		}
	}
	if(result){
		for(key in result){
			var tmp = result[key];			
			if(tmp["redirect"]){
				//alert(tmp["redirect"]);
				top.location=tmp["redirect"];
			}		
			if(tmp["act"]==0){
				$("#"+tmp["div"]).html(tmp["cont"]);
			}else if(tmp["act"]==1){
				$("#"+tmp["div"]).append(tmp["cont"]);
			}else if(tmp["act"]==2){
				$("#"+tmp["div"]).prepend(tmp["cont"]);
			}else if(tmp["act"]==3){
				$("#"+tmp["div"]).html("");
			}			
			if(tmp["style"]){
				for(var k in tmp["style"]){
					//alert(k+'=>'+tmp["style"][k]);
					ge(tmp["div"]).style[k]=tmp["style"][k];
				}
			}
			if(tmp["js"]){
				eval(tmp["js"]);
			}
					
		}
	}
}


function GetInfo(ref, npc)
	{
		if (ref != 0){
			if (ref>0) getAjax({c: 'Info', m: 'Index', 'id': ref, 'div': 'dialog'});
			else getAjax({c: 'Info', m: 'Index', 'name': ref, 'div': 'dialog'});
		}else
			getAjax({c: 'Info', m: 'Index', 'npc': npc, 'div': 'dialog'});
	}


function openDivInfo(){
	$("#PersonageInfo").show();
}
function closeDivInfo(){
	$("#PersonageInfo").hide();
}

function SendSupport()
{
	var message = $("div#win_ajax_content div.support textarea").val();
	var title = $("div#win_ajax_content div.support input.title").val();
	var title_type = $("div#win_ajax_content div.support select#type").val();
	if (title_type != 1)
	{
		title = $("div#win_ajax_content div.support select#type option:selected").text();
	}
	
	var data =
	{
		"message" 	 : message,
		"title"	  	 : title,
		"title_type" : title_type
	};
	//getAjax({c: 'Character', m: 'SendSupport', 'data': data});
}

function SupportTitleChange(value)
{
	if (value != 1)
	{
		$("div#win_ajax_content div.support .title").hide();
	}
	else
	{
		$("div#win_ajax_content div.support .title").show();
	}
}

// Фнкция обработки времени
function formatDateNull(str){
	if(str < 10){
		return "0"+str;
	}else{
		return str;
	}

}

function formatIntToTime(str){
	var theDate = new Date(str * 1000);
	var d = formatDateNull(theDate.getDate());
	var m = formatDateNull( theDate.getMonth() + 1 );
	var y = formatDateNull(theDate.getFullYear());
	var h = formatDateNull(theDate.getHours());
	var i = formatDateNull(theDate.getMinutes());

	var ret = d +"."+ m +"."+ y +" "+ h +":"+ i;
	return ret;
}


function formatSecToTime(sec){
	var a = {
			86400 : 'дней', // количество секунд в сутках
			3600  : 'час.', // количество секунд в часе
			60    : 'мин.', // количество секунд в минуте
			1     : 'сек.' // количество секунд в секунде
			}
	 var out = '';
	 for(var key in a) {
		  var tmp = Math.floor(sec/key);
		  out +=(tmp != 0) ? tmp+" "+a[key] : '';
		  sec -= tmp * key;
	 }
	 return out;
}


	


//Перемещаемые окошки 
function window_create(title, content, name, style, width, height, x, y)
{
	//Врем переменные
	var html = '';		
	var i = 0;

	//Заполняем пустые значения
	if (width == null) width = "300px";
	if (height == null) height = "100px";
	if (x == null) x = "40%";
	if (y == null) y = "40%";
	if (style == null) style = "";


	//Если имя не задано то присваиваем уник идентификатор
	if (name == null)
	{
		while ($("#window_"+i).length > 0)
		{
			i++;
			x = (40+i*2)+"%";
			y = (40+i*2)+"%";
		}
		name = i;	
	}

	//Если имя задано то чекаем не существует ли его уже						
	else
	{
		if ($("#window_"+name).length > 0)
		{
			if (content != null)
			{
				$("#window_"+name+"_content").html(content);
				$("#window_"+name).fadeIn(250);
				return name;
			}
			else
				return false;
		}
	}

	//Генерируем html
	html = 		
	"<div id=\"window_"+name+"\" style=\"display: none; position:absolute;left: "+x+"; top: "+y+"; width: "+width+"; border: 2px solid #777769;background: #e3eaca;\">"+
	"<a style=\"position: relative; top:2px; color: #eee6a3; float: right; margin-right: 4px;\" href=\"#\" onclick=\"$('#window_"+name+"').fadeOut(250)\">[x]</a>"+
	"<a style=\"position: relative; top:2px; color: #eee6a3; float: right; margin-right: 4px;\" href=\"#\" onclick=\"window_minimize('"+name+"')\">[-]</a>"+
	"<div id=\"window_"+name+"_title\" style=\"padding: 3px; background: #7ba05b; color:#960000;\">"+
	"<b>"+title+"</b>"+
	"</div>"+
	"<div id=\"window_"+name+"_content\" align=\"center\" style=\"position: relative; padding: 3px; background: #e3eaca; border: 1px solid; height: "+height+";"+style+"\">"+
	content+
	"</div>"+
	"</div>"
	;

	//Дописываем html в body
	$("body").append(html);

	//Делаем окошко переносимым
	new window_set_drag("window_"+name, "window_"+name+"_title");

	//$("#window_"+name).show();
	$("#window_"+name).fadeIn(250);

	//Возвращаем имя окна		
	return name;
}

function window_minimize(name)
{
	if ($('#window_'+name+'_content').is(":hidden"))
		$('#window_'+name+'_content').show(250);
	else
		$('#window_'+name+'_content').slideUp(250);
}

//Цепляем заголовок окна к окну для переноса	
function window_set_drag(id_div_okno,id_div_zagol)
{		

	var bIE=0; var bOp=0; var bFF=0;
	var verBr=navigator.userAgent;
	if (verBr.indexOf("Opera")!=-1)
		 bOp=1;
	  else 
	   {
	   if (verBr.indexOf("MSIE")!=-1)
		  bIE=1;
		else
		 {
		  //if (verBr.indexOf("Firefox")!=-1)
			bFF=1;
		 }
	   }			

	this.id_div_okno=id_div_okno;
	this.id_div_zagol=id_div_zagol;


	this.obj_okno=document.getElementById(this.id_div_okno);			
	this.obj_zagol_okno=document.getElementById(this.id_div_zagol);

	if (this.obj_okno == null)
	{	
		this.obj_zagol_okno=parent.document.getElementById(id_div_zagol);		
		this.obj_okno=parent.document.getElementById(id_div_okno);
		this.doc = parent.document; 
	}
	else
	{
		this.doc = document;
	}		



	this.delta_x=0;
	this.delta_y=0;

	this.setup_mouse = function()
	  {
	   var self=this;
	   this.obj_zagol_okno.onmousedown=function(o){ self.save_delta_koor(self,o) };
	   if (bOp || bFF)
		 {
		  this.obj_zagol_okno.addEventListener("onmousedown",self.save_delta_koor,false);

		 }

	   //this.obj_zagol_okno.onmouseup=self.clear_delta_koor;
	   this.doc.onmouseup=self.clear_delta_koor;
	  }

	this.save_delta_koor = function(obj_move,obj_evt)
	  {


	   if (obj_evt)
		 {
		  x=obj_evt.pageX;
		  y=obj_evt.pageY;
		 }
		else
		  {
		   x = parent.window.event.clientX;
		   y = parent.window.event.clientY;
		   if (bIE)
			 {
			  y-=2;
			  x-=2;
			 }

		  }

	   x_okno=obj_move.obj_okno.offsetLeft;
	   y_okno=obj_move.obj_okno.offsetTop;

	   obj_move.delta_x=x_okno-x;
	   obj_move.delta_y=y_okno-y;


	   this.doc.onmousemove=function(o){ obj_move.motor_okno(obj_move,o) };
	   if (bOp || bFF)
		 this.doc.addEventListener("onmousemove",obj_move.motor_okno,false);

	  }

	 if (this.doc == document)
		this.clear_delta_koor = function()
		  {
		   document.onmousemove=null;
		   //setup_mouse();

		  }
	else
		this.clear_delta_koor = function()
		  {
		   parent.document.onmousemove=null;
		   //setup_mouse();

		  }


	this.motor_okno = function(obj_move,obj_event)
	  {

	   if (obj_event)
		 {
		  x=obj_event.pageX;
		  y=obj_event.pageY;
		 }
		else
		  {
		   x=parent.window.event.clientX;
		   y=parent.window.event.clientY;
		   if (bIE)
			 {
			  y-=2;
			  x-=2;
			 }

		  }
	   new_x=obj_move.delta_x+x;
	   new_y=obj_move.delta_y+y;

	   //window.status=new_x+" "+new_y;

	   obj_move.obj_okno.style.top=new_y+"px";
	   obj_move.obj_okno.style.left=new_x+"px";

	  }

	this.setup_mouse();
}
function SelectPCur(id, cur)
{
		$("#viewperk #price_"+id+" .cur_1").removeClass("select1");
		$("#viewperk #price_"+id+" .cur_2").removeClass("select2");
		$("#viewperk #price_"+id+" .cur_"+cur).addClass("select"+cur);	
}
function BuyPerk(id)
{
	//var currency_id= $('#viewperk #price_1 input:radio[name=currency_id_1_'+id+']:checked').val();
	var money_type = 0;	
	if ($("#viewperk #price_1 .cur_1.select1").length != 0) money_type = 1;
	if ($("#viewperk #price_1 .cur_2.select2").length != 0) money_type = 2;
	if ($("#viewperk #price_1 .cur_3.select3").length != 0) money_type = 3;
	if ($("#viewperk #price_1 .cur_4.select4").length != 0) money_type = 4;
	if( money_type==0){
		alert("Не выбрана стоимость.");
	}else{
		windowManfredi.getObject('ajax')._close();
		getAjax({'c':'Perks','m':'BuyPerk', "id":id, "currency_id":money_type });
	}
}
function DownPerk(id)
{
	var money_type = 0;	
	if ($("#viewperk #price_2 .cur_1.select1").length != 0) money_type = 1;
	if ($("#viewperk #price_2 .cur_2.select2").length != 0) money_type = 2;
	if ($("#viewperk #price_2 .cur_3.select3").length != 0) money_type = 3;
	if ($("#viewperk #price_2 .cur_4.select4").length != 0) money_type = 4;
	//var currency_id= $('#viewperk #price_2 input:radio[name=currency_id_2_'+id+']:checked').val();
	windowManfredi.getObject('ajax')._close();
	getAjax({'c':'Perks','m':'DownPerk', "id":id, "currency_id":money_type });
}
function StartPerk(id)
{
	windowManfredi.getObject('ajax')._close();
	getAjax({'c':'Perks','m':'StartPerk', "id":id });
}

function BuyCPerk(id)
{
	var money_type = 0;	
	if ($("#viewperk #price_1 .cur_1.select1").length != 0) money_type = 1;
	if ($("#viewperk #price_1 .cur_2.select2").length != 0) money_type = 2;
	//if ($("#viewperk #price_1 .cur_3.select3").length != 0) money_type = 3;
	//if ($("#viewperk #price_1 .cur_4.select4").length != 0) money_type = 4;
	if( money_type==0){
		alert("Не выбрана стоимость.");
	}else{
		windowManfredi.getObject('ajax')._close();
		getAjax({'c':'Clan','m':'BuyPerk', "id":id, "currency_id":money_type });
	}
}
function DownCPerk(id)
{
	var money_type = 0;	
	if ($("#viewperk #price_2 .cur_1.select1").length != 0) money_type = 1;
	if ($("#viewperk #price_2 .cur_2.select2").length != 0) money_type = 2;
	//if ($("#viewperk #price_2 .cur_3.select3").length != 0) money_type = 3;
	//if ($("#viewperk #price_2 .cur_4.select4").length != 0) money_type = 4;
	windowManfredi.getObject('ajax')._close();
	getAjax({'c':'Clan','m':'DownPerk', "id":id, "currency_id":money_type });
}

function ChangeRecipe(num, arr){
	var recipe = $("#win_ajax_content #recipes #grade"+num+" div.recip");
	var cur = 0;
	for(var i=0; i<=recipe.length-1; i++){
		if(recipe.eq(i).hasClass("select")){
			cur = i;
		}
	}
	
	if(arr=='next' && cur<recipe.length-1){
		recipe.eq(cur+1).addClass("select");
		recipe.eq(cur).removeClass("select");
	}else if(arr=='next' ){
		recipe.eq(0).addClass("select");
		recipe.eq(cur).removeClass("select");
	}
	if(arr=='prev' && cur>0){
		recipe.eq(cur-1).addClass("select");
		recipe.eq(cur).removeClass("select");
	}else if(arr=='prev'){
		recipe.eq(recipe.length-1).addClass("select");
		recipe.eq(cur).removeClass("select");
	}
}

function SaveRule(){
	var accept = $('#win_ajax_content #cform #accept').attr('checked') == true ? 1 : 0;
	var expel = $('#win_ajax_content #cform #expel').attr('checked') == true ? 1 : 0;
	var treasury = $('#win_ajax_content #cform #treasury').attr('checked') == true ? 1 : 0;
	var diplomat = $('#win_ajax_content #cform #diplomat').attr('checked') == true ? 1 : 0;
	var business =$('#win_ajax_content #cform #business').attr('checked') == true ? 1 : 0;
	var perk = $('#win_ajax_content #cform #perk').attr('checked') == true ? 1 : 0;
	var upgrade = $('#win_ajax_content #cform #upgrade').attr('checked') == true ? 1 : 0;
	var edit = $('#win_ajax_content #cform #edit').attr('checked') == true ? 1 : 0;
	var mail = $('#win_ajax_content #cform #mail').attr('checked') == true ? 1 : 0;
	var clan_id  = $('#cform #clan_id').val();
	var user_id =  $('#cform #user_id').val();
	windowManfredi.getObject('ajax')._close();
	getAjax({'c':"Clan",'m':"SaveRule", 'clan_id':clan_id, 'user_id':user_id, 'accept':accept,'expel':expel, 'treasury':treasury, 'diplomat':diplomat,'business':business, 'perk':perk, 'upgrade':upgrade, 'edit':edit, 'mail':mail });}

// Сущетствует ли картинка
function isImage(strUrl)
{
	return true;
	var resultCheck = true;
	image = document.createElement('img');
	image.src = strUrl;
	image.onerror = function(){
	    var resultCheck = false;
	};
	if ((image.width == 0) && (image.height == 0))
	{
		return false;
	}
	return resultCheck;
}


// Получить всех участников клана
function attackUser(id)
{
	getAjax({"c":"Battle", "m":"attackUserByClan", "id": id});
	windowManfredi.getObject('ajax')._close();
}

// Обменник - смена иконки предмета на которую хотим обменять ресурс
function changerChangeImg(id)
{
	$("div#resChanger img#changeImg").attr("src", iServer+'/i/items/item_'+id+'.png');
}

// Получить всех участников клана
function getPlayers(id)
{
	getAjax({"c":"Battle", "m":"getClanWarList", "id": id});	
}

// Квест, описания шмоток для награды
questAwards = {};
function setAwards(data)
{
	questAwards = data;
}

// Квест, распечатка описания предметов
function printQuestDesc()
{
	var html = '';
	if (questAwards["items"])
	{
		for(var key in questAwards["items"])
		{
			if (questAwards["items"][key]["item"])
			{
				html = printItemDescription(questAwards["items"][key]["item"]);			
				$("#quest_item_"+questAwards["items"][key]["item"]["id"]).attr("title", html);
			}
		}
		$(".quest_item").hoverbox();
	}
}

// Для главной страници 
function chScreenScene(id)
{
	// Кнопки
	$("a.gbutton").removeClass("hover");
	$("a#gbutton"+id).addClass("hover");
	
	// Панельки
	$("div.screenScene").hide();	
	$("div#screenScene"+id).show();	
}

function photoMove(shift, obj)
{
	var ox = $(obj).parent().find("div.photoContent").position().left;
	
	var mox = 0;
	$(obj).parent().find("div.photoContent a").each(function(index, o){
		mox += $(o).width()+10;
	});	
	
	ox -= shift;	
	
	mox += 7;
	
	if (ox > 5)
		ox = 5;
	if (ox-780 < -mox)
		ox = -mox+780;		
		
	$(obj).parent().find("div.photoContent").animate({left: ox, queue: false}, 300);
}

// Патрулирование
function Patrol(id){
	var time = $("#win_ajax_content #patrol_"+id+" #time").val();
	if(time>0){
		windowManfredi.getObject('ajax')._close();
		getAjax({"c":"Location", "m":"StartPatrol", "patrol_id":id, "time":time});
		
	}else{
		alert('Выберите длительность патруля.');
	}
}

/*
 * version: 1.0.4
 * package: OrangeBox
 * author: David Paul Hamilton - http://orangebox.davidpaulhamilton.net
 * copyright: Copyright (c) 2011 David Hamilton / DavidPaulHamilton.net All rights reserved.
 * license: GNU/GPL license: http://www.gnu.org/copyleft/gpl.html
 */
var ob_fadeInTime=200,ob_fadeOutTime=200,
ob_overlayOpacity=0.9,ob_maxVideoHeight=390,
ob_maxVideoWidth=640,ob_preloaderDelay=600,
ob_unsupportedMedia_Message="Unsupported Media",
ob_fileNotFound_Message="File Not Found",
ob_showDots=true,ob_showNav=true,ob_showClose=true,
ob_showTitle=true,ob_keyboardNavigation=true,
ob_contentBorderWidth=4,ob_contentMinHeight=100,ob_contentMinWidth=200,ob_imageBorderWidth=1,ob_inineWidth=0.5,ob_inineHeight=0,ob_maxImageHeight=0.75,ob_maxImageWidth=0.75,ob_iframeWidth=0.75,ob_iframeHeight=0.75;(function($){$.fn.extend({orangebox:function(){return this.each(function(){$(this).click(function(e){var modalTitle=$('<div id="ob_title"></div>'),modalClose='<div title="close" id="ob_close"></div>',modalNavRight=$('<a class="ob_nav" id="ob_right"><span id="ob_right-ico"></span></a>'),modalNavLeft=$('<a class="ob_nav" id="ob_left"><span id="ob_left-ico"></span></a>'),modalContent=$('<div id="ob_content"></div>'),overlay=$('<div id="ob_overlay"></div>'),modalWindow=$('<div id="ob_window"></div>'),modalContainer=$('<div id="ob_container"></div>'),modalFloat=$('<div id="ob_float"></div>'),dotnav=$('<ul id="ob_dots"></ul>'),ob_load=$('<div id="ob_load"></div>'),t,imageType=[".jpg",".png",".jpeg",".bmp",".gif"],quicktimeType=[".mov",".mp4",".m4v"],lightboxlink='a[rel=lightboxlink]',mainhref=$(this).attr("href"),maintitle=$(this).attr("title"),rel=$(this).attr('rel'),height,width,galleryItems=new Array(),titles=new Array(),currentIndex,progress=null,s,isError=false,content,gallery,scrollPos,docHeight=$(window).height(),docWidth=$(window).width();if(docHeight===0){docHeight=$(document).height();}if(docWidth===0){docWidth=$(document).width();}function getScrollPos(){var pos=$(window).scrollTop();if(pos===0){pos=$(document).scrollTop();}if(pos===0){pos=window.pageYOffset;}return pos;}scrollPos=getScrollPos();overlay.css({"opacity":ob_overlayOpacity,"min-width":docWidth,"min-height":docHeight+scrollPos});modalContent.css({"border-width":ob_contentBorderWidth,"min-height":ob_contentMinHeight,"min-width":ob_contentMinWidth});window.onscroll=function(){var newPos=getScrollPos();if(newPos>scrollPos){var scrolltimer=setTimeout(function(){overlay.css({"height":newPos+docHeight});scrollPos=newPos;clearTimeout(scrolltimer);},300);}};e.preventDefault();if(typeof document.body.style.maxHeight==="undefined"){$("body","html").css({height:"100%",width:"100%"});}t=setTimeout(function(){$("body").append(ob_load);},ob_preloaderDelay);function checkContentType(itemhref){if(itemhref==="ob_hidden_set"){return"ob_hidden_set";}if(itemhref.match(/\?iframe$/)){return"iframe";}if(itemhref.match(/\.(?:jpg|jpeg|bmp|png|gif)$/)){return"image";}if(itemhref.match(/\.(?:mov|mp4|m4v)(\?.{6,}\&.{6,})?$/)){return"quicktime";}if(itemhref.match(/\.swf(\?.{6,}\&.{6,})?$/)){return"flash";}if(itemhref.match(/^http:\/\/\w{0,3}\.?youtube\.\w{2,3}\/watch\?v=[\w\-]{11}/)){return"youtube";}if(itemhref.match(/^http:\/\/\w{0,3}\.?vimeo\.com\/\d{1,10}/)){return"vimeo";}if(itemhref.match(/^#/)){return"inline";}return;}if(rel.substring(8)){gallery=rel.substring(rel.indexOf("[")+1,rel.indexOf("]"));}if(gallery){var arrayID=0,objectMatch='a[rel*=\'lightbox['+gallery+']\']';$(objectMatch).each(function(){var itemhref=$(this).attr("href"),title=$(this).attr("title"),contentType=checkContentType(mainhref),inGallery=jQuery.inArray(itemhref,galleryItems);if(contentType&&inGallery===-1&&itemhref!=="ob_hidden_set"){galleryItems[arrayID]=itemhref;titles[arrayID]=title;if(ob_showDots){if(arrayID===0){dotnav.append('<li class="current" id="ob_dot'+arrayID+'"></li>');}else{dotnav.append('<li id="ob_dot'+arrayID+'"></li>');}}arrayID++;}});if($('#ob_gallery').length>0){$('#ob_gallery li.'+gallery).each(function(){var itemhref=$(this).attr("id"),title=$(this).attr("title"),contentType=checkContentType(mainhref),inGallery=jQuery.inArray(itemhref,galleryItems);if(contentType&&inGallery===-1){galleryItems[arrayID]=itemhref;titles[arrayID]=title;if(ob_showDots){dotnav.append('<li id="ob_dot'+arrayID+'"></li>');}arrayID++;}});}}function navigate(href,title){clearTimeout(t);t=setTimeout(function(){$("body").append(ob_load);},ob_preloaderDelay);modalWindow.fadeOut(ob_fadeOutTime,function(){content.empty();modalTitle.empty().remove();modalContent.empty().remove();modalWindow.empty().remove();modalContainer.empty();var contentType=checkContentType(href);if(contentType==="iframe"){showiFrame(href,title);}else if(contentType==="image"){showImage(href,title);}else if(contentType==="inline"){showInline(href,title);}else if(contentType==="quicktime"){showVideo(href,title,contentType);}else if(contentType==="youtube"){showVideo(href,title,contentType);}else if(contentType==="vimeo"){showVideo(href,title,contentType);}else if(contentType==="flash"){showVideo(href,title,contentType);}});}function navigateHandler(index){if(galleryItems[index]){var href=galleryItems[index],title=titles[index];currentIndex=index;navigate(href,title);}else{progress=null;}}function showNavigation(currenthref){for(var i=0;i<galleryItems.length;i++){if(galleryItems[i]==currenthref){currentIndex=i;};}if(ob_showDots){modalWindow.append(dotnav);dotnav.find("li").click(function(){if(!$(this).hasClass('current')){var id=$(this).attr('id'),newid=id.substr(6);dotnav.find("li").removeClass('current');$(this).addClass('current');navigateHandler(newid);}});}if(ob_showNav){modalWindow.append(modalNavRight).append(modalNavLeft);if(galleryItems[currentIndex+1]){modalNavRight.show();}else{modalNavRight.hide();};if(galleryItems[currentIndex-1]){modalNavLeft.show();}else{modalNavLeft.hide();};modalNavLeft.click(function(e){e.stopPropagation();navigateHandler(currentIndex-1);});modalNavRight.click(function(e){e.stopPropagation();navigateHandler(currentIndex+1);});}}function handleEscape(e){if(progress==null){progress="running";if(e.keyCode==27){modalHide();}else if(e.keyCode==37){navigateHandler(currentIndex-1);}else if(e.keyCode==39){navigateHandler(currentIndex+1);}else{progress=null;};};}function modalHide(){$(document).unbind("keydown",handleEscape);var remove=function(){$(this).remove().empty();};clearTimeout(t);ob_load.remove();overlay.fadeOut(ob_fadeOutTime,remove);modalContainer.fadeOut(ob_fadeOutTime,remove);}$("body").append(overlay.click(function(){modalHide();}));$("body").append(modalContainer.click(function(){modalHide();}));if(ob_keyboardNavigation){$(document).keydown(handleEscape);}overlay.show(ob_fadeInTime);function setModalProperties(){var objectHeight=content.outerHeight(),objectWidth=content.outerWidth(),windowHeight=objectHeight+(ob_contentBorderWidth*2),windowWidth=objectWidth+(ob_contentBorderWidth*2);if(windowHeight<ob_contentMinHeight&&isError===false){windowHeight=ob_contentMinHeight+(ob_contentBorderWidth*2);}if(windowWidth<ob_contentMinWidth&&isError===false){windowWidth=ob_contentMinWidth+(ob_contentBorderWidth*2);}modalContainer.css({"margin-top":getScrollPos()});modalWindow.css({"height":windowHeight,"width":windowWidth});if(isError){modalContent.css({"height":objectHeight,"width":objectWidth,"min-height":0});}else{modalContent.css({"height":windowHeight-(ob_contentBorderWidth*2),"width":windowWidth-(ob_contentBorderWidth*2),"min-height":ob_contentMinHeight});}modalFloat.css({"margin-bottom":-windowHeight/2});modalWindow.click(function(e){e.stopPropagation();});$(lightboxlink).click(function(e){e.preventDefault();e.stopPropagation();navigate($(this).attr('href'),$(this).attr('title'))});if(ob_showDots){var current='#ob_dot'+currentIndex;dotnav.find("li").removeClass('current');$(current).addClass('current');}progress=null;}function getValue(href){var heightIndex=href.indexOf("height=")+7,widthIndex=href.indexOf("width=")+6,heightString=href.substr(heightIndex),widthString=href.substr(widthIndex);if(heightString.indexOf("&")>0){heightString=heightString.substr(0,heightString.indexOf("&"));}if(widthString.indexOf("&")>0){widthString=widthString.substr(0,widthString.indexOf("&"));}width=widthString;height=heightString;}function buildit(title,href){clearTimeout(t);ob_load.remove();modalTitle.append('<h3>'+title+'</h3>');modalContent.append(content);modalWindow.append(modalContent);if(ob_showClose){modalWindow.append(modalClose);};if(ob_showTitle){modalWindow.append(modalTitle);};if(galleryItems.length>1)showNavigation(href);modalContainer.append(modalFloat).append(modalWindow);modalWindow.fadeIn(ob_fadeInTime);$("#ob_close").click(function(){modalHide();});setModalProperties();}function throwError(type){var message;if(type==1){message=ob_unsupportedMedia_Message;}else if(type==2){message=ob_fileNotFound_Message;}content=$('<div id="ob_error">'+message+'</div>');clearTimeout(t);ob_load.remove();modalContent.empty().append(content);modalWindow.empty().append(modalContent);if(ob_showClose){modalWindow.append(modalClose);};modalContainer.empty().append(modalFloat).append(modalWindow);modalWindow.fadeIn(ob_fadeInTime);$("#ob_close").click(function(){modalHide();});isError=true;setModalProperties();isError=false;}function showiFrame(href,title){var args='height="100%" width="100%" frameborder="0" hspace="0" scrolling="auto"',newhref=href.replace(/\?iframe$/,'');newhref=newhref.replace(/\?iframe\&/,'?');newhref=newhref.replace(/\&iframe/,'');content=$('<iframe id="ob_iframe" '+args+' src="'+newhref+'"></iframe>');if(ob_iframeWidth>1){content.css({"width":ob_iframeWidth});}else if(ob_iframeWidth>0){content.css({"width":docWidth*ob_iframeWidth});}if(ob_iframeHeight>1){content.css({"height":ob_iframeHeight});}else if(ob_iframeHeight>0){content.css({"height":docHeight*ob_iframeHeight});}buildit(title,href);}function showInline(href,title){content=$('<div id="ob_inline">'+$(href).html()+'</div>');if(ob_inineWidth>1){content.css({"width":ob_inineWidth});}else if(ob_inineWidth>0){content.css({"width":docWidth*ob_inineWidth});}if(ob_inineHeight>1){content.css({"height":ob_inineHeight});}else if(ob_inineHeight>0){content.css({"height":docHeight*ob_inineHeight});}buildit(title,href);}function showVideo(href,title,contentType){var idIndex,ID,ratio=0,maxHeight,maxWidth;if(ob_maxVideoHeight>1){maxHeight=ob_maxVideoHeight;}else if(ob_maxVideoHeight>0){maxHeight=docHeight*ob_maxVideoHeight;}if(ob_maxVideoWidth>1){maxWidth=ob_maxVideoWidth;}else if(ob_maxVideoWidth>0){maxWidth=docWidth*ob_maxVideoWidth;}if(href.indexOf("height=")>=0&&href.indexOf("width=")>=0){getValue(href);if(height>maxHeight){ratio=maxHeight/height;width=width*ratio;height=maxHeight;};if(width>maxWidth){ratio=maxWidth/width;height=height*ratio;width=maxWidth;};}else{width=maxWidth;height=maxHeight;};var paramStart='<div><object width="'+width+'" height="'+height+'"><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><param name="movie" value="';var paramEnd='type="application/x-shockwave-flash" allowfullscreen="true" allowscriptaccess="always" width="'+width+'" height="'+height+'"></embed></object></div>';if(contentType=="youtube"){idIndex=href.indexOf("?v=")+3;if(href.indexOf("&")>idIndex){ID=href.substring(idIndex,href.indexOf("&"));}else{ID=href.substring(idIndex);};content=$(paramStart+'http://www.youtube.com/v/'+ID+'?fs=1&hl=en_US&rel=0&autoplay=1"></param><embed src="http://www.youtube.com/v/'+ID+'?fs=1&hl=en_US&rel=0&autoplay=1"'+paramEnd);}else if(contentType=="vimeo"){idIndex=href.indexOf("vimeo.com/")+10;if(href.indexOf("?")>idIndex){ID=href.substring(idIndex,href.indexOf("?"));}else{ID=href.substring(idIndex);};content=$(paramStart+'http://vimeo.com/moogaloop.swf?clip_id='+ID+'&server=vimeo.com&show_title=0&show_byline=0&show_portrait=0&color=ff9933&fullscreen=1&autoplay=1&loop=0"></param><embed src="http://vimeo.com/moogaloop.swf?clip_id='+ID+'&server=vimeo.com&show_title=0&show_byline=0&show_portrait=0&color=ff9933&fullscreen=1&autoplay=1&loop=0"'+paramEnd);}else if(contentType=="quicktime"){content=$('<div><object classid="clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B" codebase="http://www.apple.com/qtactivex/qtplugin.cab" height="'+height+'" width="'+width+'"><param name="src" value="'+href+'"><param name="type" value="video/quicktime"><param name="autoplay" value="true"><embed src="'+href+'" height="'+height+'" width="'+width+'" autoplay="true"  type="video/quicktime" pluginspage="http://www.apple.com/quicktime/download/" scale="aspect"></object></div>');}else if(contentType=="flash"){content=$('<div><embed flashVars="playerVars=autoPlay=yes" src="'+href+'" wmode="transparent" pluginspage="http://www.macromedia.com/go/getflashplayer" allowFullScreen="true" allowScriptAccess="always" width="'+width+'" height="'+height+'" type="application/x-shockwave-flash"></embed></div>');};content.css({"width":width,"height":height});buildit(title,href);}function showImage(href,title){var img=new Image();content=$(img);content.load(function(){var maxHeight=0,maxWidth=0,ratio=0;if(ob_maxImageHeight>1){maxHeight=ob_maxImageHeight;}else if(ob_maxImageHeight>0){maxHeight=docHeight*ob_maxImageHeight;}if(ob_maxImageWidth>1){maxWidth=ob_maxImageWidth;}else if(ob_maxImageWidth>0){maxWidth=docWidth*ob_maxImageWidth;}width=img.width;height=img.height;if(height>maxHeight){ratio=maxHeight/height;width=width*ratio;height=maxHeight;}if(width>maxWidth){ratio=maxWidth/width;height=height*ratio;width=maxWidth;}if(height<ob_contentMinHeight){content.css({"margin-top":(ob_contentMinHeight/2)-(height/2)});}if(width<ob_contentMinWidth){content.css({"margin-left":(ob_contentMinWidth/2)-(width/2)});}content.css({"height":parseInt(height),"width":parseInt(width),"border-width":ob_imageBorderWidth});buildit(title,href);}).error(function(){throwError(2);}).attr({src:href});}var contentType=checkContentType(mainhref);if(contentType==="ob_hidden_set"){mainhref=galleryItems[0];maintitle=titles[0];contentType=checkContentType(mainhref);}if(contentType==="iframe"){showiFrame(mainhref,maintitle);}else if(contentType==="image"){showImage(mainhref,maintitle);}else if(contentType==="inline"){showInline(mainhref,maintitle);}else if(contentType==="quicktime"){showVideo(mainhref,maintitle,contentType);}else if(contentType==="youtube"){showVideo(mainhref,maintitle,contentType);}else if(contentType==="vimeo"){showVideo(mainhref,maintitle,contentType);}else if(contentType==="flash"){showVideo(mainhref,maintitle,contentType);}else{throwError(1);}});});}});})(jQuery);$(function(){$('a[rel*=lightbox]').orangebox();})
